<?php

namespace app\api\controller\meet\product;

use app\common\controller\Api;
use app\common\model\meet\product\Product;
use app\common\model\meet\Service;
use app\common\model\meet\Store;

/**
 * 产品接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     *
     * @var Product
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();

        $this->model = new Product();
    }

    public function index()
    {
        $category_id = $this->request->get('category_id/d', 0);
        $storeId = $this->request->get("storeId/d");
        $category_model = new \app\common\model\meet\Category();

        $parent_category_list = $category_model->where(['status' => $category_model::STATUS_NORMAL, 'id' => $category_id])->order('weigh', 'desc')->column('id');

        $product_list = [];
        if (!empty($parent_category_list)) {
            $category_list = [];
            foreach ($parent_category_list as $k => $pid) {
                $list = $category_model->where(['pid' => $pid, 'status' => $category_model::STATUS_NORMAL])->field('id,name,nickname,image,keywords')->order('weigh', 'desc')->select();

                if ($list) {
                    $category_list = array_reduce(collection($list)->toArray(), function ($carry, $item) {
                        $carry[] = $item;
                        return $carry;
                    }, $category_list);
                }
            }

            if ($category_list) {
                foreach ($category_list as $key => $value) {

                    $list = $this->model->where([
                        'category_id' => $value['id'],
                        'status' => $this->model::STATUS_NORMAL,
                        'store_id'=>$storeId
                    ])->field('id,name,cover_image')->order('weigh', 'desc')->select();

                    foreach ($list as $k => $v) {
                        $v['cover_image'] = cdnurl($v['cover_image'], true);
                    }

                    $value['product_list'] = $list ? collection($list)->toArray() : [];

                    $product_list[] = $value;
                }
            }
        }

        $this->success('', ['list' => $product_list]);
    }

    public function search()
    {
        $keywords = $this->request->get('keywords/s', '');

        if (empty($keywords)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $condition = [
            'status' => $this->model::STATUS_NORMAL,
            'name' => ['like', "%{$keywords}%"]
        ];

        $list = $this->model->where($condition)->field('id,name,images')->order('weigh', 'desc')->select();

        if ($list) {
            foreach ($list as $key => $value) {
                $images = explode(',', $value['images']);
                $value['image'] = cdnurl($images[0], true);
            }
        }

        $this->success('', ['list' => $list]);
    }

    public function detail()
    {
        $id = $this->request->get('id/d', 0);

        if (empty($id)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $condition = [
            'id' => $id,
            'status' => $this->model::STATUS_NORMAL
        ];

        $detail = $this->model->with(['spec', 'specRel'])->where($condition)->find();

        if (empty($detail)) {
            $this->error(__('The product does not exist'));
        }

        $detail['cover_image'] = cdnurl($detail['cover_image'], true);

        $images_arr = explode(',', $detail['images']);

        foreach ($images_arr as $k => $v) {
            $images_arr[$k] = cdnurl($v, true);
        }

        $detail['images'] = $images_arr;

        foreach ($detail['spec'] as $key => $value) {
            $value['spec_image_full'] = $value['spec_image'] ? cdnurl($value['spec_image'], true) : cdnurl($images_arr[0], true);
        }

        if (!empty($detail['content'])) {
            $domain = request()->domain();
            $detail['content'] = str_replace('<img src="/uploads/', '<img src="' . $domain . '/uploads/', $detail['content']);
        }

        // 规格信息
        $specData = $detail['spec_type'] === '20' ? $detail->getManySpecData($detail['spec_rel'], $detail['spec']) : null;

        // 这里对规格的img格式化
        if ($specData != null) {
            foreach ($specData['spec_list'] as $index => $item) {
                $specData['spec_list'][$index]["form"]['imgshow'] = $specData['spec_list'][$index]["form"]['spec_image'] === '' ? cdnurl($images_arr['0'], true) : cdnurl($specData['spec_list'][$index]["form"]['spec_image'], true);
            }
        }

        //服务和交付标准
        $service_list = [];

        if ($detail['service_ids']) {
            $service_ids_arr = explode(',', $detail['service_ids']);

            $service_list = Service::where(['status' => Service::STATUS_NORMAL, 'id' => ['in', $service_ids_arr]])->field('id,title,image')->order('weigh', 'desc')->select();
        }

        $this->success('', ['detail' => $detail, 'specData' => $specData, 'service_list' => $service_list ?: []]);
    }

    public function getStoreInfo()
    {
        $product_id = $this->request->get('product_id/d', 0);

        $longitude = $this->request->get('longitude', '');

        $latitude = $this->request->get('latitude', '');

        if (empty($product_id)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $condition = [
            'id' => $product_id,
            'status' => $this->model::STATUS_NORMAL
        ];

        $product_info = $this->model->where($condition)->find();

        if (empty($product_info)) {
            $this->error(__('The product does not exist'));
        }

        if ($latitude && $longitude) {
            $store_info = Store::where('id', '=', $product_info->store_id)->field('id,name,address,longitude,latitude,telephone,truncate(ACOS(SIN((' . $latitude . ' * 3.1415) / 180 ) *SIN((latitude * 3.1415) / 180 ) +COS((' . $latitude . ' * 3.1415) / 180 ) * COS((latitude * 3.1415) / 180 ) *COS((' . $longitude . ' * 3.1415) / 180 - (longitude * 3.1415) / 180 ) ) * 6380 * 1000,0) as distance')->find();
        } else {
            $store_info = Store::where('id', '=', $product_info->store_id)->field('id,name,address,longitude,latitude,telephone')->find();
        }


        if (empty($store_info)) {
            $this->error(__('No results were found'));
        }

        if (isset($store_info['distance']) && $store_info['distance'] > 0) {
            $store_info['distance'] = (float)bcdiv($store_info['distance'], 1000, 2);
        } else {
            $store_info['distance'] = 0;
        }

        $this->success('', $store_info);
    }

    public function reservationDate()
    {
        $start_date = $this->request->get('start_date/s', '');//开始日期

        if (empty($start_date)) {
            $start_date = date('Y-m-d', time());
        }

        $today_date = date('Y-m-d', time());

        $dateTime = new \DateTime($start_date);


        $date_list = [];

        $week_array = ['日', '一', '二', '三', '四', '五', '六'];

        for ($i = 0; $i < 14; $i++) {
            // 克隆当前日期对象以避免修改原始对象
            $cloneDate = clone $dateTime;

            // 使用 modify 方法增加天数
            $cloneDate->modify('+' . $i . ' days');
            // 将格式化后的日期字符串添加到数组中
            $date = $cloneDate->format('Y-m-d');
            $date_list[$i]['date'] = $date;
            $date_list[$i]['date_sub'] = $cloneDate->format('m-d');
            $date_list[$i]['week'] = '周' . $week_array[date('w', strtotime($date))];
            $date_list[$i]['is_today'] = $today_date === $date ? 1 : 0;
            $date_list[$i]['checked'] = $i === 0 ? 1 : 0;
        }

        $this->success('', ['list' => $date_list]);
    }

    public function reservationTime()
    {
        $store_id = $this->request->get('store_id/d', '');
        $date = $this->request->get('date/s', '');

        if (empty($store_id) || empty($date)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $store_info = Store::where('id', '=', $store_id)->field('id,time_interval')->find();

        if (empty($store_info)) {
            $this->error(__('No results were found'));
        }

        $time_interval = $store_info->time_interval ? explode(',', $store_info->time_interval) : [];

        $list = [];

        foreach ($time_interval as $k => $v) {
            $data = [
                'time' => $v,
                'date' => $date,
                'timestamp' => strtotime($date . ' ' . $v),
                'checked' => 0,
                'status' => 0,//0-可选，1-已选，2-不可约，3-不显示
            ];

            if ($data['timestamp'] < time()) {
                $data['status'] = 3;
            }

            $list[] = $data;
        }

        $this->success('', ['list' => $list]);
    }
}
